package com.zsc.springcloud.annotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 限流AOP
 */
@Slf4j
@Component
@Aspect
public class AccessLimiterAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> redisScript;

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.zsc.springcloud.annotation.AccessLimiter)")
    public void cut(){
        log.info("cut");
    }


    @Before("cut()")
    public void before(JoinPoint joinPoint){
        // 1.获取方法签名，作为method key
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AccessLimiter accessLimiter = method.getAnnotation(AccessLimiter.class);
        if (accessLimiter == null){
            return;
        }
        String methodKey = accessLimiter.methodKey();
        int limit = accessLimiter.limit();
        if(StringUtils.isBlank(methodKey)){
            methodKey = method.getName();
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes != null){
                String paramType = Arrays.stream(parameterTypes).map(Class::getName).collect(Collectors.joining(","));
                log.info("param type is :" + paramType);
                methodKey += "#" + paramType;
            }
        }
        // 2.调用redis
        boolean acquired = stringRedisTemplate.execute(
                redisScript,
                Lists.newArrayList(methodKey),
                String.valueOf(limit)
        );
        // 脚本返回false,则返回异常
        if (!acquired){
            log.error("your access is blocked,key={}",methodKey);
            throw new RuntimeException("your access is blocked");
        }
    }
}
